{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "b64f1212",
   "metadata": {},
   "outputs": [],
   "source": [
    "import asyncio\n",
    "import os\n",
    "import shutil\n",
    "\n",
    "from agents import Agent, Runner, gen_trace_id, trace, OpenAIChatCompletionsModel\n",
    "from agents.mcp import MCPServer, MCPServerStdio\n",
    "from openai import AsyncOpenAI\n",
    "from dotenv import load_dotenv\n",
    "load_dotenv()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5b63ccc3",
   "metadata": {},
   "outputs": [],
   "source": [
    "api_key = os.environ[\"NEBIUS_API_KEY\"]\n",
    "base_url = \"https://api.tokenfactory.nebius.com/v1\" \n",
    "client = AsyncOpenAI(base_url=base_url, api_key=api_key)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "0c3a957e",
   "metadata": {},
   "outputs": [],
   "source": [
    "async def qna(agent):\n",
    "    message = \"Tell me about the database that you are connected to.\"\n",
    "    print(f\"Running: {message}\")\n",
    "    result = await Runner.run(starting_agent=agent, input=message)\n",
    "    print(result.final_output)\n",
    "\n",
    "    message = \"List out the top 5 hotels by the highest aggregate rating?\"\n",
    "    print(f\"\\n\\nRunning: {message}\")\n",
    "    result = await Runner.run(starting_agent=agent, input=message)\n",
    "    print(result.final_output)\n",
    "\n",
    "    message = \"Recommend me a flight and hotel from New York to San Francisco\"\n",
    "    print(f\"\\n\\nRunning: {message}\")\n",
    "    result = await Runner.run(starting_agent=agent, input=message)\n",
    "    print(result.final_output)\n",
    "\n",
    "    message = \"I'm going to the UK for 1 week. Recommend some great spots to visit for sightseeing. Also mention the respective prices of those places for adults and kids.\"\n",
    "    print(f\"\\n\\nRunning: {message}\")\n",
    "    result = await Runner.run(starting_agent=agent, input=message)\n",
    "    print(result.final_output)\n",
    "\n",
    "    message = \"My budget is around 30 pounds a night. What will be the best hotel to stay in?\"\n",
    "    print(f\"\\n\\nRunning: {message}\")\n",
    "    result = await Runner.run(starting_agent=agent, input=message)\n",
    "    print(result.final_output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "c8ed2f11",
   "metadata": {},
   "outputs": [],
   "source": [
async def run(mcp_server: MCPServer):
    agent = Agent(
        name="Assistant",
        instructions="""Couchbase organizes data with the following hierarchy (from top to bottom):

                        1. Cluster

                        The overall container of all Couchbase data and services.

                        2. Bucket

                        A bucket is similar to a database in traditional systems.

                        Each bucket contains multiple scopes.

                        Example: "users", "analytics", "products"

                        3. Scope

                        A scope is a namespace within a bucket that groups collections.

                        Scopes help isolate data for different microservices or tenants.

                        Default scope name: _default

                        4. Collection

                        The equivalent of a table in relational databases.

                        Collections store JSON documents.

                        Default collection name: _default

                        5. Document

                        The atomic data unit (usually JSON) stored in a collection.

                        Each document has a unique key within its collection.

                        Use the tools to read the database answer questions based on this database.
                        The data is inside `inventory` scope, so use only that scope.
                        Any query you generate needs to have only the collection name in the FROM clause.
                        Every field, collection, scope or bucket name inside the query should be inside backticks.""",
        model=OpenAIChatCompletionsModel(
            model="meta-llama/Meta-Llama-3.1-8B-Instruct",
            openai_client=client
        ),
        mcp_servers=[mcp_server],
    )

    await qna(agent=agent)
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "e08f8d4c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Starting CouchbaseDemo\n",
      "View trace: https://platform.openai.com/traces/trace?trace_id=trace_ab0900977661443e926dd61304dc06e0\n",
      "\n",
      "Running: Tell me about the database that you are connected to.\n",
      "I am connected to a database that has the following organizational structure:\n",
      "\n",
      "- There are multiple scopes (namespaces), each containing collections (similar to tables in a SQL database).\n",
      "- The main scope containing data of interest is called inventory.\n",
      "\n",
      "Within the inventory scope, there are five collections:\n",
      "1. airport\n",
      "2. airline\n",
      "3. route\n",
      "4. landmark\n",
      "5. hotel\n",
      "\n",
      "Each collection stores data as JSON documents, and these collections likely cover information related to airports, airlines, travel routes, notable landmarks, and hotels.\n",
      "\n",
      "Other scopes, such as tenant_agent_00 to tenant_agent_04, seem to have collections related to users and bookings, possibly for a multi-tenant application. There are also default and system-specific scopes and collections.\n",
      "\n",
      "If you want to know about the structure or data in any particular collection, please specify which one!\n",
      "\n",
      "\n",
      "Running: List out the top 5 hotels by the highest aggregate rating?\n",
      "The top 5 hotels by highest aggregate (average) rating are:\n",
      "\n",
      "1. Belle Cour Hotel & SPA - 5.0\n",
      "2. Lovett House Guest House - 5.0\n",
      "3. Hotel del Coronado - 5.0\n",
      "4. Hôtel Acacias Etoile - 5.0\n",
      "5. Handlery Hotel - 5.0\n",
      "\n",
      "All of these hotels have an average \"Overall\" review rating of 5.0.\n",
      "\n",
      "\n",
      "Running: Recommend me a flight and hotel from New York to San Francisco\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Errored MCP tool result: meta=None content=[] isError=False\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Here are my recommendations for your trip from New York to San Francisco:\n",
      "\n",
      "Flight:\n",
      "- Airline: Alaska Airlines (AS)\n",
      "- Route: Nonstop from JFK (New York) to SFO (San Francisco)\n",
      "- Sample Flight: AS717, departing at 01:41 UTC (other time options available through the week)\n",
      "- Distance: Approx. 4,152 km\n",
      "\n",
      "Hotel in San Francisco:\n",
      "- Name: Inn on Castro\n",
      "- Address: 321 Castro St, San Francisco, California, United States\n",
      "- Description: An upscale bed and breakfast in a restored house, located at 16th street.\n",
      "- Amenities: Free internet, free parking, pet-friendly, no free breakfast.\n",
      "- Website: [Inn on Castro](http://www.innoncastro.com/)\n",
      "- Price range: $95–$190\n",
      "- Phone: +1 415 861-0321\n",
      "\n",
      "Would you like more details or assistance with booking?\n",
      "\n",
      "\n",
      "Running: I'm going to the UK for 1 week. Recommend some great spots to visit for sightseeing. Also mention the respective prices of those places for adults and kids.\n",
      "Here are some great sightseeing spots in the UK (Glasgow) for your 1-week trip, along with prices for adults and kids where available:\n",
      "\n",
      "1. Glasgow Cathedral\n",
      "   - Description: A magnificent Gothic cathedral dating from medieval times, built on a site first consecrated in 397AD. Nearby is the Necropolis, a historic and grand cemetery.\n",
      "   - Price: Free (for all ages)\n",
      "\n",
      "2. City Chambers (George Square)\n",
      "   - Description: An Italian Renaissance style building, headquarters of the City Council. Free daily tours showing stunning interiors.\n",
      "   - Price: Free (for all ages)\n",
      "\n",
      "3. St Enoch Subway Station\n",
      "   - Description: Historic subway station in a quaint building, currently used as a coffee shop, located in St Enoch Square.\n",
      "   - Price: Free (for all ages)\n",
      "\n",
      "4. Glasgow Central Station\n",
      "   - Description: Glasgow’s principal railway terminus, noted for its grand interior and the impressive glass-walled bridge known as the Hielanman's Umbrella.\n",
      "   - Price: Free (for all ages)\n",
      "\n",
      "5. Glasgow School of Art (Mackintosh at the GSA Tour)\n",
      "   - Description: One of Britain’s most important art schools. Although the original building is closed, external tours are available focusing on Mackintosh’s architecture.\n",
      "   - Price: £9.75 adults, £8 students/seniors, £4.75 youth\n",
      "\n",
      "6. Mitchell Library\n",
      "   - Description: The largest municipal public reference library in Europe with a stunning reading room. Great for book lovers.\n",
      "   - Price: Free (for all ages)\n",
      "\n",
      "7. Glasgow University (Hunterian Museum and Art Gallery)\n",
      "   - Description: Historic university (founded 1451), includes the excellent Hunterian Museum and Art Gallery, and impressive neo-Gothic architecture.\n",
      "   - Price: Free (for all ages)\n",
      "\n",
      "8. Scotland Street School (Museum)\n",
      "   - Description: Designed by Charles Rennie Mackintosh, features an excellent museum about Mackintosh and educational history.\n",
      "   - Price: Free (for all ages)\n",
      "\n",
      "9. House for an Art Lover\n",
      "   - Description: Built to Mackintosh’s original 1901 designs, with an excellent museum and beautiful surroundings. Includes audio handset guide.\n",
      "   - Price: £4.50 adults, £3 youth/students\n",
      "\n",
      "10. Holmwood House\n",
      "   - Description: A stunning example of Alexander ‘Greek’ Thomson’s work, run by the National Trust and currently being renovated.\n",
      "   - Price: £6.50 adults, £16.50 family, £5 concession\n",
      "\n",
      "These attractions cover culture, history, and architecture—with many offering free entry! Be sure to check for updated prices and opening hours before your visit. If you need spots in other cities (like London), let me know!\n",
      "\n",
      "\n",
      "Running: My budget is around 30 pounds a night. What will be the best hotel to stay in?\n",
      "Here are some of the best hotel options in the UK for around £30 a night, along with notable features and guest feedback:\n",
      "\n",
      "---\n",
      "### **1. Anis Louise Guest House, Chesterfield**\n",
      "- **Price:** £27 per night\n",
      "- **Address:** 34 Clarence Road, Chesterfield, United Kingdom\n",
      "- **Facilities:** Free breakfast, free internet, pets not allowed, no free parking\n",
      "- **Reviews:** Not many available, but it's the best fit for your budget in the UK and appears clean and straightforward.\n",
      "\n",
      "**Recommendation:** If your priority is value, cleanliness, and location over luxury, this is your best choice for under £30/night.\n",
      "\n",
      "---\n",
      "\n",
      "### **2. Tan yr Eglwys Cottages, Pontardawe (Budget option, but with strong caveats)**\n",
      "- **Price:** £ (exact amount unclear, but marked as pound-priced and likely budget—verify final price before booking)\n",
      "- **Address:** Church Road, Cilybebyll, Pontardawe, SA8 3JR, United Kingdom\n",
      "- **Facilities:** Free breakfast, free parking, pets allowed, no free internet\n",
      "- **Reviews:** Mixed, averaging very poor to average. Some guests report cleanliness and facilities issues, others felt it was tolerable given the price.\n",
      "\n",
      "**Recommendation:** Only choose if you are highly budget-restricted and everywhere else is unavailable—but reviews warn about subpar conditions!\n",
      "\n",
      "---\n",
      "\n",
      "### **3. Other Notable Options (Above Budget)**\n",
      "If you're able to stretch a bit above £30:\n",
      "- **La Reserve Hotel Chelsea, London** – £95, great staff and facilities according to reviews.\n",
      "- **Hotel Sergul, London** – £40, but mixed reviews on comfort and amenities.\n",
      "- **Magazine Wood B&B, Norfolk** – £40, nice environment and guest comfort, but just over your budget.\n",
      "\n",
      "---\n",
      "\n",
      "### **Summary**\n",
      "Your best bet **under £30 is Anis Louise Guest House in Chesterfield**—it fits your budget, offers free breakfast and WiFi, and has no significant negative reviews.\n",
      "\n",
      "If you book here, you’ll have a reliable, no-nonsense stay within your budget. If you need something in London or other big cities, consider stretching your budget a little or look for hostels/guesthouses with similar pricing but read reviews carefully.\n",
      "\n",
      "Would you like more details or booking info for any hotel above?\n"
     ]
    }
   ],
   "source": [
    "async with MCPServerStdio(\n",
    "    params={\n",
    "        \"command\": \"/Users/shivaylamba/miniconda3/bin/uv\",\n",
    "        \"args\": [\"--directory\", \"/Users/shivaylamba/Documents/work/mcp-server-couchbase\",\n",
    "                    \"run\",\n",
    "                    \"--env-file\", \"/Users/shivaylamba/Documents/work/MCPCouchbaseDemo/src/.env\",\n",
    "                \"src/mcp_server.py\"],\n",
    "    }\n",
    ") as server:\n",
    "    trace_id = gen_trace_id()\n",
    "    with trace(trace_id=trace_id, workflow_name=\"CouchbaseDemo\"):\n",
    "        print(\"Starting CouchbaseDemo\")\n",
    "        print(f\"View trace: https://platform.openai.com/traces/trace?trace_id={trace_id}\\n\")\n",
    "        await run(server)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "33a36e43",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
